import { useUserStore } from "./user";
import { useAccessStore } from "./access";
import type { LoginType } from "@/config/types";
import { loginByPwd } from "@/api/auth/login";
import { getUserDetail } from "@/api/system/user";
import { preferences } from "@/config/preference";
import router from "@/router/index";

export const useAuthStore = defineStore("auth", () => {
  const userStore = useUserStore();
  const accessStore = useAccessStore();

  const login = async (params: Api.LoginByPwdReq, loginType: LoginType = "password") => {
    if (loginType === "password") {
      const [err, res] = await loginByPwd(params);
      if (!err) {
        let token = res.accessToken;
        let useId = res.userId;
        accessStore.setAccessToken(token);
        accessStore.setAccessUserId(useId);
        userStore.setUserInfo(res);
        router.push({ path: preferences.app.home });
      }
    }
  };

  const fetchUserDetail = async () => {
    // console.log("userInfo: ", accessStore.userId);
    if (accessStore.userId) {
      let params = { id: accessStore.userId };
      const [err, res] = await getUserDetail(params, { loading: true });
      if (!err) {
        userStore.setUserDetail(res);
      }
    }
  };

  const logout = () => {
    accessStore.clearAccess();
    userStore.clearUserInfo();
  };

  return { login, logout, fetchUserDetail };
});
